package com.bookbuf.mockdb;

import com.bookbuf.bean.Task;
import com.bookbuf.bean.User;
import com.bookbuf.service.TaskService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by robert on 16/7/23.
 */
public class MockTaskDatabase implements TaskService {

    static WrapperCollect collect = new WrapperCollect();

    @Override
    public boolean insert(User user, Task task) {
        collect.add(user, task);
        return true;
    }

    @Override
    public boolean update(User user, Task task) {
        try {
            collect.update(user, task);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public boolean delete(User user, Task task) {
        return false;
    }

    @Override
    public List<Task> query(User user, String condition) {
        return collect.get(user);
    }

    private static class WrapperCollect {
        private volatile int index = 0;
        private HashMap<User, List<Task>> db = new HashMap<>();

        private int increase() {
            return ++index;
        }

        public void add(User user, Task task) {
            if (db.containsKey(user)) {
                List<Task> tasks = db.get(user);
                task.setId(increase());
                tasks.add(task);
            } else {
                List<Task> tasks = new ArrayList<>();
                task.setId(increase());
                tasks.add(task);
                db.put(user, tasks);
            }
            System.out.println("插入任务:" + task.getId());
        }

        public void update(User user, Task task) throws Exception {
            if (db.containsKey(user)) {
                List<Task> tasks = db.get(user);
                boolean found = false;
                for (Task item : tasks) {
                    if (item.getId() == task.getId()) {
                        found = true;
                        System.out.printf("更新前:" + item.toString());
                        item = task; // 更新引用
                        System.out.printf("更新后:" + item.toString());
                        break;
                    }
                }
                if (!found) {
                    throw new RuntimeException("该条记录不再数据库中,出错退出.");
                }
            } else {
                throw new RuntimeException("该条记录不再数据库中,出错退出.");
            }
        }

        public List<Task> get(User user) {
            if (db.containsKey(user)) {
                List<Task> tasks = db.get(user);
                System.out.println("获取任务条目:" + tasks.size());
                return tasks;
            } else {
                System.out.println("获取任务条目:" + 0);
                return new ArrayList<>();
            }
        }

    }
}
